from curses import start_color
import os
import os.path as osp
import time
from tkinter.messagebox import NO
from cv2 import imwrite
import numpy as np
import pickle
import struct
import re
import cv2
from scipy import rand
from secretstorage import get_all_collections
from tqdm import tqdm
import imageio
import json
from PIL import Image
from multiprocessing import Pool
# import threadpool
# import threading
from collections import defaultdict
import random
import copy
from ctypes import CDLL,byref,create_string_buffer,cdll
from PIL import Image, ImageColor, ImageFont, ImageDraw, ImageFilter
import sys
import imgaug as ia
import imgaug.augmenters as iaa
import imgaug.parameters as iap
from imgaug.augmentables.polys import Polygon, PolygonsOnImage


from tool import filesystem,imgaug_tool,utils, data_enhance, via_tool # export PYTHONPATH=$PYTHONPATH:`pwd`



def aug_image_for_egg(image):
    io_images = []


    io_images.append(image)


    sometimes = lambda aug: iaa.Sometimes(0.5, aug)

    seq = iaa.Sequential(
        [
            # iaa.AdditiveGaussianNoise(scale=(0.01 * 255)),
                # iaa.Affine(
                #     scale={"x": (0.9, 1.1), "y": (0.9, 1.1)}, # scale images to 80-120% of their size, individually per axis
                #     translate_percent={"x": (-0.2, 0.2), "y": (-0.2, 0.2)}, # translate by -20 to +20 percent (per axis)
                #     rotate=(-20, 20), # rotate by -45 to +45 degrees
                #     shear=(-16, 16), # shear by -16 to +16 degrees
                #     order=[0, 1], # use nearest neighbour or bilinear interpolation (fast)
                #     cval=(0, 255), # if mode is constant, use a cval between 0 and 255
                #     mode=ia.ALL # use any of scikit-image's warping modes (see 2nd image from the top for examples)
                # ),
                # iaa.Rotate(rotate=(-15, 15)),

                # iaa.Dropout(p=(0.01, 0.1), per_channel=0.5),
                iaa.LinearContrast((0.8,1.2), per_channel=1),
                iaa.Add((-10, 10), per_channel=1),


                iaa.OneOf([
                    iaa.AverageBlur(k=1),
                    iaa.GaussianBlur((0, 1.0)),
                    iaa.MedianBlur(k=(1,3)),
                    iaa.AverageBlur(k=(1,3)),
                    iaa.JpegCompression(compression=(70, 95)),
                    # iaa.pillike.FilterBlur(),
                    iaa.pillike.FilterSmooth(),
                ]),

                iaa.OneOf([
                    iaa.Salt(0.1),

                    # iaa.OneOf([
                        # iaa.imgcorruptlike.DefocusBlur(severity=1),

                        # iaa.AveragePooling(1),
                        # iaa.imgcorruptlike.Contrast(severity=1),
                        iaa.imgcorruptlike.JpegCompression(severity=1),
                        
                    # ]),

                    # iaa.imgcorruptlike.ZoomBlur(severity=2),
                    iaa.imgcorruptlike.Fog(severity=1),
                    iaa.imgcorruptlike.Frost(severity=1),
                    iaa.imgcorruptlike.Snow(severity=1),
                    iaa.imgcorruptlike.Spatter(severity=1),

                    # iaa.imgcorruptlike.Pixelate(severity=1),

                ]),


        ],
        random_order=False
    )

    image_aug = seq(images=io_images)
    return image_aug[0]



def iou(rect1, rect2):
    y0 = np.max([rect1[1],rect2[1]])
    y1 = np.min([rect1[1] + rect1[3],rect2[1]+rect2[3]])

    x0 = np.max([rect1[0],rect2[0]])
    x1 = np.min([rect1[0] + rect1[2],rect2[0]+rect2[2]])
    return x1 > x0 and y1 > y0


def GenNewCh(f,val, w=45, h=90, color = (0,0,0)):
    img=Image.new("RGBA", (w,h),(0,0,0,0))
    draw = ImageDraw.Draw(img)
    draw.text((0, 0),val,color,font=f)
    return img

def convert_gbk_to_utf8(text_dir):
    replace_text = ["　", "：", "∶", "；", "？", "！", "，", "．", "～", "〜", "＠", "＆", "％", "＃", 
        "＄", "＼", "／", "“", "〃", "”", "＂", "＇", "｀", "‘", "’", "＋", "＝", "〓", "＊", "－", 
        "–", "—", "―", "─", "｜", "＿", "＜", "＞", "（", "）", "｛", "｝", "〔", "〕", "￥", "Ⅴ", 
        "、", "。", "※", "÷", "〈", "〉", "《", "》", "【", "】", "±", "≤", "≥", "‰", "·", "ˇ", 
        "•", "ˉ", "¨", "「", "」", "『", "』", "︿", "〖", "〗", "‖", "…", "^", "?", 
        "!", ",", "`", ".", "~", "@", "&", "%", "#", "$", "\\", "\"", "/", "'", "×", "+", 
        "=", "*", "-", "|", "丨", "_", "<", ">", "(", ")", "{", "}", "[", "]", "℃", "①", 
        "②", "③", "④", "⑤", "⑥", "⑦", "⑧", "⑨", "０", "１", "２", "３", "４", "５", 
        "６", "７", "８", "９", "Ａ", "А", "Ｂ", "Β", "Ｃ", "С", "Ｄ", "Ｅ", "Ｆ", "Ｇ", 
        "Ｈ", "Η", "Ｉ", "Ｊ", "Ｋ", "Κ", "Ｌ", "└", "Ｍ", "м", "М", "Ｎ", "Ｏ", "Ｐ", 
        "Р", "Ｑ", "Ｒ", "Ｓ", "Ｔ", "Τ", "Ｕ", "Ｖ", "Ｗ", "Ｘ", "Ｙ", "Υ", "Ｚ"]

    for idx, path in enumerate(filesystem.get_all_filepath(text_dir, [".txt"])):
        with open(path, "r", encoding="gb18030") as rf:
            text = rf.read()
        for t in replace_text:
            text = text.replace(t, "")

        wf = open(osp.join(osp.dirname(path), "utf8_" + osp.basename(path)), "w", encoding="utf8")
        wf.write(text)
        wf.close()

class TextImageGenerator:
    def __init__(self):
        # self.plate_type = current_type
        # self.current_name = current_name

        # self.fontCE = ImageFont.truetype(fontChEng[self.plate_type], 128, 0)    # 省简称使用字体
        # self.pil_img = Image.new("RGBA", (440, 140), (0, 0, 0,0))
        self.font_paths = filesystem.get_all_filepath(FONT_DIR)
        self.alpha_font_paths = filesystem.get_all_filepath(ALPHA_FONT_DIR)

        # [[idx, text],[idx, text],...]
        self.texts = self.load_text(TEXT_DIR)

    # 生成文本行图片
    def gen_text_line_image(self, pil_img, text, w=45, h=90):
        """

        """
        pts = []
        labels = []
        offset = 0
        # string_length = 8 if self.plate_type == 1 else 7
        string_length = 7
        if self.plate_type == 1:
            color = (5,5,5)
            first_points = [0,0,0,0]

            pil_img.paste(GenNewCh(self.fontCE, text[0], 45, 90, color), (offset+15, 25))
            first_points[0] = [offset+15, 25]
            first_points[3] = [offset+15, 25+90]

            offset += 15+45
            for i in range(string_length-1):
                if i == 1:
                    offset += 40 
                offset += 9 
                if text[i+1] != "x":
                    w = 43 
                    pil_img.paste( GenNewCh(self.fontCE, text[i+1], w, 90, color), (offset, 25))

                offset += 43 

                if i == string_length -2:
                    first_points[1] = [offset, 25]
                    first_points[2] = [offset, 25+90]

            pts.append(first_points)
            labels.append(text)

        return pil_img, pts, labels

    def load_text(self, text_dir):
        texts = []
        for idx, path in enumerate(filesystem.get_all_filepath(text_dir, [".txt"])):
            with open(path, "r", encoding="utf8") as rf:
                text = rf.read()
            text = text.replace(" ", "").replace("\n", "").replace("\t", "")
            # print(idx, text)
            texts.append([0, text])
        return texts

    def gen_text_img(self, xyxy, font_size, text_color, min_length, max_length):
        '''
        根据固定区域, 随机生成区域内n个字符
        '''
        text_len = len(self.texts)
        text_idx = random.randint(0, text_len-1)

        start_idx = self.texts[text_idx][0]
        end_idx = start_idx + random.randint(min_length, max_length)

        font = random.choice(self.font_paths)
        imagefont = ImageFont.truetype(font=font, size=font_size-2)
        text_width = text_height = 0
        test_str = None
        while end_idx > start_idx:
            test_str = self.texts[text_idx][1][start_idx:end_idx]
            text_width, text_height = imagefont.getsize(test_str)
            if text_width < (xyxy[2] - xyxy[0]):
                break
            end_idx -= 1
        
        if end_idx == start_idx: return None
        self.texts[text_idx][0] = end_idx
        
        txt_img = Image.new('RGBA', (text_width, text_height), (0, 0, 0, 0))
        txt_draw = ImageDraw.Draw(txt_img)
        colors = [ImageColor.getrgb(c) for c in text_color.split(',')]
        c1, c2 = colors[0], colors[-1]
        fill = (
            random.randint(c1[0], c2[0]),
            random.randint(c1[1], c2[1]),
            random.randint(c1[2], c2[2])
        )
        txt_draw.text((0, 0), test_str, fill=fill, font=imagefont)

        return txt_img


        
    def find_suitable_paste_rect(self, mask, choice_row, try_cnt):
        
        while try_cnt > 0:
            try_cnt -= 1 
            row_idx = random.choice(range(len(choice_row)))
            start_y = 0
            end_y = choice_row[row_idx]
            if row_idx != 0:
                start_y = choice_row[row_idx-1]
            y = (start_y + end_y) // 2

            x = random.randint(50, mask.shape[1]-50)
            
            start_x = x
            end_x = x
            for sx in range(x, 0, -1):
                if mask[y, sx] == 0:
                    start_x = sx
                else:
                    break
            for sx in range(x, mask.shape[1], 1):
                if mask[y, sx] == 0:
                    end_x = sx
                else:
                    break
            
            # 相等表示此处已经被占用
            if start_x == end_x:
                continue

            median_x = (start_x+end_x)//2
            # update start_y end_y
            while mask[start_y, median_x] > 0:
                start_y += 1
            while mask[end_y, median_x] > 0:
                end_y -= 1 
            return [start_x, start_y, end_x, end_y]
        return None


    def random_add_text(self, img, mask, lines, thickness, times, min_length, step, try_cnt):
        """
        随机添加文字
        """

        height, width = img.shape[:2]
        choice_row = [x for x in range(step,height-step, step)]
        choice_col = [x for x in range(step,width-step, step)]
        if len(choice_row) == 0 or len(choice_col) == 0:
            return None
        # print("add_line: ", add_line)

        for t in range(times):
            
            xyxy = self.find_suitable_paste_rect(mask, choice_row, try_cnt)
            if xyxy is None: continue

            text_color = "#000000,#303030"
            font_size = random.randint(int(step*0.4), int(step*0.8))
            txt_img = self.gen_text_img(xyxy, font_size, text_color, 2, 10)
            if txt_img is None: continue
        
        
            image_array = np.frombuffer(txt_img.tobytes(), dtype=np.uint8)
            image_array = image_array.reshape((txt_img.size[1], txt_img.size[0], 4))
            ori_img = image_array[:,:,:3]
            ori_img = ori_img[:, :, ::-1]
            ori_mask = image_array[:,:,3]
            
            y_max_diff = xyxy[3] - xyxy[1] - ori_img.shape[0]
            x_max_diff = xyxy[2] - xyxy[0] - ori_img.shape[1]
            if y_max_diff <= 1: continue
            if x_max_diff <= 1: continue
            y_start = random.randint(1, y_max_diff)
            x_start = random.randint(1, x_max_diff)

            cv2.rectangle(mask, (xyxy[0]+x_start, xyxy[1]), (xyxy[0]+x_start+ori_img.shape[1], xyxy[3]), (255), -1)
            paste_img = img[xyxy[1]+y_start:xyxy[1]+y_start+ori_img.shape[0], xyxy[0]+x_start:xyxy[0]+x_start+ori_img.shape[1]]
            cv2.copyTo(ori_img, ori_mask, paste_img)

        return img

    def gen_one_char(self, xyxy, step):
        text_color = "#000000,#303030"
        font_size = random.randint(int(step*0.4), int(step*0.6))
        font = random.choice(self.alpha_font_paths)
        imagefont = ImageFont.truetype(font=font, size=font_size)
        test_str = random.choice(["A", "B", "C", "D", "E", "F", "G", "H"])
        text_width, text_height = imagefont.getsize(test_str)
        if text_width >= (xyxy[2] - xyxy[0]): return None, None
        
        txt_img = Image.new('RGBA', (text_width, text_height), (0, 0, 0, 0))
        txt_draw = ImageDraw.Draw(txt_img)
        colors = [ImageColor.getrgb(c) for c in text_color.split(',')]
        c1, c2 = colors[0], colors[-1]
        fill = (
            random.randint(c1[0], c2[0]),
            random.randint(c1[1], c2[1]),
            random.randint(c1[2], c2[2])
        )
        txt_draw.text((0, 0), test_str, fill=fill, font=imagefont)

        image_array = np.frombuffer(txt_img.tobytes(), dtype=np.uint8)
        image_array = image_array.reshape((txt_img.size[1], txt_img.size[0], 4))
        ori_img = image_array[:,:,:3]
        ori_img = ori_img[:, :, ::-1]
        ori_mask = image_array[:,:,3]
        
        # 去除多余部分
        col_sum = np.sum(ori_mask, axis=0)
        col_index = np.where(col_sum>0)[0]
        col_start = col_index[0]
        col_end = col_index[-1] +1
        
        row_sum = np.sum(ori_mask, axis=1)
        row_index = np.where(row_sum>0)[0]
        row_start = row_index[0]
        row_end = row_index[-1] +1
        ori_mask = ori_mask[row_start:row_end, col_start:col_end]
        ori_img = ori_img[row_start:row_end, col_start:col_end]
            
        return ori_img, ori_mask

    def random_add_box(self, img, mask, lines, thickness, times, min_length, step, try_cnt):
        """
        随机添加票选框
        """

        height, width = img.shape[:2]
        choice_row = [x for x in range(step,height-step, step)]
        choice_col = [x for x in range(step,width-step, step)]
        if len(choice_row) == 0 or len(choice_col) == 0:
            return None
        # print("add_line: ", add_line)
        
        boxs = []
        for t in range(times):
            
            xyxy = self.find_suitable_paste_rect(mask, choice_row, try_cnt)
            # print("xyxy: ", xyxy)
            if xyxy is None: continue

            if random.randint(0,1):
                char_img, char_mask = self.gen_one_char(xyxy, step)
                if char_img is None: continue
                # pad to square
                left = right = top = bottom = 0
                if char_img.shape[0] > char_img.shape[1]:
                    diff = char_img.shape[0] - char_img.shape[1]
                    left = diff // 2
                    right = diff // 2 + (1 if diff % 2 == 1 else 0)
                if char_img.shape[0] < char_img.shape[1]:
                    diff = char_img.shape[1] - char_img.shape[0]
                    top = diff // 2
                    bottom = diff // 2 + (1 if diff % 2 == 1 else 0)
                char_img = cv2.copyMakeBorder(char_img, top, bottom, left, right, cv2.BORDER_CONSTANT)
                char_mask = cv2.copyMakeBorder(char_mask, top, bottom, left, right, cv2.BORDER_CONSTANT)

                # 多余的空间
                border = random.randint(0,4)
                char_img = cv2.copyMakeBorder(char_img, border, border, border, border, cv2.BORDER_CONSTANT)
                char_mask = cv2.copyMakeBorder(char_mask, border, border, border, border, cv2.BORDER_CONSTANT)
            else:
                wh = random.randint(int(step*0.4), int(step*0.6))
                char_img = np.zeros((wh, wh, 3), np.uint8)
                char_mask = np.zeros((wh, wh), np.uint8)
            
            # 红框
            border = random.randint(2,5)
            box_img = cv2.copyMakeBorder(char_img, border, border, border, border, cv2.BORDER_CONSTANT, value=(0,0,255))
            box_mask = cv2.copyMakeBorder(char_mask, border, border, border, border, cv2.BORDER_CONSTANT, value=(255))

            # 2pix 外围空间
            box_img = cv2.copyMakeBorder(box_img, 2, 2, 2, 2, cv2.BORDER_CONSTANT, value=(0,0,0))
            box_mask = cv2.copyMakeBorder(box_mask, 2, 2, 2, 2, cv2.BORDER_CONSTANT, value=(0))


            # cv2.imwrite("box_img.jpg", box_img)
            # cv2.imwrite("box_mask.jpg", box_mask)
        
            y_max_diff = xyxy[3] - xyxy[1] - box_img.shape[0]
            x_max_diff = xyxy[2] - xyxy[0] - box_img.shape[1]
            if y_max_diff <= 1: continue
            if x_max_diff <= 1: continue
            y_start = random.randint(1, y_max_diff)
            x_start = random.randint(1, x_max_diff)

            # 竖向全部mask
            cv2.rectangle(mask, (xyxy[0]+x_start, xyxy[1]), (xyxy[0]+x_start+box_img.shape[1], xyxy[3]), (255), -1)
            box_xyxy = [xyxy[0]+x_start, xyxy[1]+y_start, xyxy[0]+x_start+box_img.shape[1], xyxy[1]+y_start+box_img.shape[0]]
            paste_img = img[box_xyxy[1]:box_xyxy[3], box_xyxy[0]:box_xyxy[2]]
            boxs.append([box_xyxy[0] , box_xyxy[1], box_xyxy[2]-box_xyxy[0], box_xyxy[3]-box_xyxy[1]])
            cv2.copyTo(box_img, box_mask, paste_img)

        return boxs


    def random_add_line(self, img, mask, thickness, times, min_length, step):
        """
        随机任意方向增加直线, 模拟表格
        """
        
        height, width = img.shape[:2]

        choice_row = [x for x in range(step,height-step, step)]
        choice_col = [x for x in range(step,width-step, step)]
        if len(choice_row) == 0 or len(choice_col) == 0:
            return None
        # print("add_line: ", add_line)

        lines = []
        for t in range(times):
            vertical = random.randint(0,1)

            if vertical:
                col = random.choice(choice_col)
                row_s = random.randint(1, max(2, height - min_length-1))
                row_e = random.randint(min(row_s+min_length, height-2), height-1)
                p1 = (col, row_s)
                p2 = (col, row_e)
            else:
                row = random.choice(choice_row)
                col_s = random.randint(1, max(2, width - min_length-1))
                col_e = random.randint(min(col_s+min_length, width-2), width-1)
                p1 = (col_s, row)
                p2 = (col_e, row)
            lines.append([p1, p2])
            cv2.line(img, p1, p2, (0,0,255), thickness)
            cv2.line(mask, p1, p2, (255), thickness)
            
        return lines

    def save_json(self, save_dir, save_info, polygon_flag=False, via_name="via_region_data.json"):
        save_dict = {}

        for file_path, boxs in save_info.items():

            one_data = dict()
            filename = os.path.basename(file_path)
            one_data["filename"] = filename
            file_size = os.path.getsize(file_path)
            one_data["size"] = file_size

            regions = []
            for box in boxs:

                region = dict()
                region["region_attributes"] = {"label": "box"}
                if polygon_flag == "polygon":
                    region["shape_attributes"] = {"name": "polygon",
                                                    "all_points_x": [int(x[0]) for x in new_region_info[idx]],
                                                    "all_points_y": [int(x[1]) for x in new_region_info[idx]]}
                else:
                    region["shape_attributes"] = {"name": "rect",
                                                    "x": box[0],
                                                    "y": box[1],
                                                    "width" : box[2],
                                                    "height" : box[3]
                                                    }  
                regions.append(region)
            one_data["regions"] = regions
            one_data["file_attributes"] = {}
            save_dict[filename+str(file_size)] = one_data

        with open(save_dir + os.sep + via_name, "w") as wf:
            wf.write(json.dumps(save_dict))

    def run(self, start_idx, images_in_per_dir, via_name="via_region_data_ori.json"):

        save_dir = osp.join(SAVE_DIR, str(start_idx))
        if os.path.exists(save_dir):
            print("continue: ", save_dir)
            return 
        os.makedirs(save_dir, exist_ok=True)

        save_info = {}
        for idx in tqdm(range(images_in_per_dir)):
            img_idx = start_idx + idx

            new_w = random.randint(400, 1000)
            new_h = random.randint(400, 1000)
            bgr_img = np.zeros((new_h, new_w, 3), np.uint8) + np.array((255,255,255), np.uint8)
            mask = np.zeros((new_h, new_w), np.uint8)

            step = random.randint(40, 70)
            thickness = random.randint(1,5)
            times = random.randint(15,35)
            min_length = min(new_h, new_w) // 2
            lines = self.random_add_line(bgr_img, mask, thickness, times, min_length, step)
            if lines is None: continue

            try_cnt = 10
            times = random.randint(15,35)
            ret = self.random_add_text(bgr_img, mask, lines, thickness, times, min_length, step, try_cnt)
            if ret is None: continue

            try_cnt = 20
            times = random.randint(35, 100)
            boxs = self.random_add_box(bgr_img, mask, lines, thickness, times, min_length, step, try_cnt)
            if boxs is None: continue

            # imgaug
            bgr_img = aug_image_for_egg(bgr_img)

            save_path = osp.join(save_dir, "{}.jpg".format(img_idx))
            cv2.imwrite(save_path, bgr_img)
            # save_mask_path = osp.join(save_dir, "{}.mask.jpg".format(img_idx))
            # cv2.imwrite(save_mask_path, mask)

            save_info[save_path] = boxs


        self.save_json(save_dir, save_info)


def convert_to_rect_points(data_dir, via_name="via_region_data.json"):
    with open(data_dir + os.sep + via_name) as rf:
        data_dict = json.loads(rf.read())

    new_data_dict = dict()
    for k in data_dict.keys():
        item = data_dict[k]
        regions = via_tool.read_via_polygon_to_rect_imp(item["regions"])
        for pts, label in regions:
            if label == "retain":continue
            region = dict()
            shape_attributes = dict()
            shape_attributes["name"] = "polygon"
            all_points_x = []
            all_points_y = []
            for xy in pts:
                all_points_x.append(int(xy[0]))
                all_points_y.append(int(xy[1]))
            shape_attributes["all_points_x"] = all_points_x
            shape_attributes["all_points_y"] = all_points_y
            region["shape_attributes"] = shape_attributes
            region["region_attributes"] = {"label": "plate"}
            item["regions"].append(region)
        new_data_dict[k] = item

    with open(data_dir + os.sep + "via_region_data_ori.json", "w") as wf:
        wf.write(json.dumps(new_data_dict))

def thread_run(start_idx, images_in_per_dir):
    tig = TextImageGenerator()
    tig.run(start_idx, images_in_per_dir)
    print("over...")

if __name__ == "__main__":

    total_count = 6           # via文件夹的个数
    total_type = [0, 1, 2, 3, 4, 5]   # 类型总数
    images_in_per_dir = 500

    thread_count = 12

    FONT_DIR = "/home/xc/work/code/python_script/resource/font"
    ALPHA_FONT_DIR = "/home/xc/work/code/python_script/resource/font2"
    TEXT_DIR = "/home/xc/work/code/python_script/resource/text/utf8"
    SAVE_DIR = "/home/xc/work/code/paddle/train_data/det/vote/images"


    total_count = 50
    p = Pool(thread_count)
    for idx, name in enumerate(range(total_count)):
        # thread_run(idx*images_in_per_dir, images_in_per_dir)
        p.apply_async(thread_run, args=(idx*images_in_per_dir, images_in_per_dir))
    p.close()
    p.join()
    while True: time.sleep(3)
    print('All subprocesses done.')

    # # 1. convet gbk to ut8
    # text_dir = "/home/xc/work/code/python_script/resource/text/gbk"
    # convert_gbk_to_utf8(text_dir)


    # # 1. 生成车牌
    # gen_plate_background()
    # gen_new_green_plate_background()   # new_green_template
    # gen_yellow_plate_background()
    # gen_double_yellow_plate_background()
    # gen_black_plate_background()
    # gen_white_plate_background

    # # 2. 制作车牌背景图片 绿牌
    # data_dir = "/media/swls/disk1/vanlance/project/plate_recognition/font/new_green_template"
    # save_dir = "/media/swls/disk1/vanlance/project/plate_recognition/font/new_green_template_2"
    # crop_image(data_dir, save_dir)

    # # 在车牌背景图片上增加四个瞄点
    # TEMPLATE_IMAGES = "/mnt/disk1/vanlance/project/plate_recognition/font/template_black"
    # TEMPLATE_IMAGES = "/media/swls/disk1/vanlance/project/plate_recognition/font/yellow_template"
    # # TEMPLATE_IMAGES = "/media/swls/disk1/vanlance/project/plate_recognition/font/new_green_template_2"
    # add_four_anchor_for_plate(TEMPLATE_IMAGES)

    ## 将标记的轮廓转化为矩形 四点
    # data_dir = "/home/swls/work_dir/github/paddle/train_data/det/plate/images/0_0_0_3_via"
    # convert_to_rect_points(data_dir, "via_region_data.json")

"""

cd /home/swls/work_dir/git/python_script && conda activate tf3 && export PYTHONPATH=$PYTHONPATH:`pwd` && sh sunjie/plate_recognition/gen_plate_0.sh

@2020-01-08     修改 warp_perspective 函数默认参数
                修改车牌背景图片颜色选取方式
                增强车牌相似字符
"""